<?php
/**
 * Created by PhpStorm.
 * User: vanity
 * Date: 2018/1/5
 * Time: 11:21
 */
namespace Admin\Controller;
use Think\Controller;
class RoleController extends CommonController
{
    protected $fields = [
        'name' => '',
        'description' => '',
    ];
    public function index()
    {
        $role = D('Role')->select();
        $this->assign('role',$role);
        $this->display();
    }
    public function create()
    {
        $data = [];
        foreach($this->fields as $field => $value){
            $data[$field] = $value;
        }
        $this->assign('data',$data);
        $this->display();
    }
    public function store()
    {
        $role = D('Role');
        $data = $role->create();
        if(!$data){
            $this->withError($role->getError(),U('admin/role/create'));
        }
        $res = $role->add();
        if(!$res){
            $this->withError('添加失败',U('admin/role/create'));
        }
        D('PermissionRole')->setPermission($res,$_POST['permission_id']);
        $this->withSuccess('添加成功',U('admin/role/index'));

    }
    public function edit()
    {
        $id = intval($_REQUEST['id']);
        $map['id'] = $id;
        $role = D('Role')->where($map)->relation('permission_role')->find();
        foreach(array_keys($this->fields) as $field){
            $data[$field] = $role[$field];
        }
        $data['id'] = $id;
        $data['permission_role'] = $role['permission_role'];
        $this->assign('data',$data);
        $this->display();
    }
    public function update()
    {
        $url = U('admin/role/edit',array('id'=>$_POST['id']));
        $role = D('Role');
        $data = $role->create();
        if(!$data){
            $this->withError($role->getError(),$url);
        }
       if(!$role->save()){
           $this->withError('修改失败',$url);
       }
        D('PermissionRole')->setPermission($_POST['id'],$_POST['permission_id']);
        $this->withSuccess('修改成功',U('admin/role/index'));
    }
    public function delete()
    {
        $id = intval($_POST['id']);
        $url = U('admin/role/index');
        if($id == ''|| $id == 0){
            $this->withError('信息丢失！',$url);
        }
        $user = D('Role');
        $map['id'] = $id;
        $result = $user->where($map)->relation(true)->delete();
        if(!$result){
            $this->withError('删除失败',$url);
        }
        $this->withSuccess('删除成功',$url);
    }
}